package com.itrip.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.aliyuncs.utils.StringUtils;
import com.itrip.dto.ResponseDTO;
import com.itrip.redisconfig.AlipayConfig;
import com.itrip.service.OrderService;
import com.itrip.service.PayService;
import com.itrip.vo.pay.OrderPayStatusVo;
import com.itrip.vo.pay.PayVo;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Api(tags = "支付宝支付接口")
@ApiResponses({
        @ApiResponse(code =100,message = "支付成功",response = ResponseDTO.class)
})
@RestController
public class PayController {

    @Resource
    private PayService payService;

    @Resource
    private OrderService orderService;



    @ApiOperation("订单支付")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "用户登陆令牌",dataType = "String",paramType = "header")
    })
    @GetMapping("/PayOrder")
    public ResponseDTO PayOrder(HttpServletRequest request, PayVo payVo) throws AlipayApiException {
        /*
        直接将这4个数据提交给支付宝后台，得到支付结果
        将tradeNo存入数据库，修改数据库订单状态
        * */
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
       /* alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);*/


        alipayRequest.setBizContent("{\"out_trade_no\":\""+ payVo.getTradeNo() +"\","
                + "\"total_amount\":\""+ payVo.getTradeAmount() +"\","
                + "\"subject\":\""+ payVo.getTradeName() +"\","
                + "\"body\":\""+ payVo.getTradeDesc() +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


        String result = alipayClient.pageExecute(alipayRequest).getBody();

        if(!StringUtils.isEmpty(result))
            return new ResponseDTO(100,"请求成功",result);

        return new ResponseDTO(101,"请求失败",result);
    }




    @ApiOperation("查询订单状态,有错误")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "用户登陆令牌",dataType = "String",paramType = "header")
    })
    @GetMapping("/view/CheckOrderPayStatus")
    public ResponseDTO CheckOrderPayStatus(OrderPayStatusVo orderPayStatusVo) throws AlipayApiException {

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        //商户订单号，商户网站订单系统中唯一订单号
        //String out_trade_no = new String(request.getParameter("WIDTQout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        String orderNo=orderPayStatusVo.getOrderNo();
        //支付宝交易号
        String tradeNo=orderPayStatusVo.getTradeNo();
        //请二选一设置

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ orderNo +"\","+"\"trade_no\":\""+ tradeNo +"\"}");

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        System.out.println(result);
        JSONObject resultObject = JSONObject.parseObject(result);
        System.out.println(resultObject.get("alipay_trade_query_response")+">>"+resultObject.get("alipay_trade_query_response").getClass());
        Map<String,String> map= (Map<String, String>) resultObject.get("alipay_trade_query_response");
        String code = map.get("code");
        System.out.println(code);
        if("40004".equals(code)&&!StringUtils.isEmpty(code)){
             Integer count = orderService.modifyOrderStatus(orderPayStatusVo);
            return new ResponseDTO(101,"交易失败",null);
        }

        //交易成功修改订单状态
        Integer count = orderService.modifyOrderStatus(orderPayStatusVo);
        return new ResponseDTO(100,"交易成功",null);
    }




}
